package hehe;

import app.behavior.LogBehavior;
import app.entity.UserEntity;
import app.service.Address;
import extend.db.DbManager;
import extend.db.base.Query;
import extend.db.base.SqlMap;
import extend.db.base.Dao;
import hehe.aop.Aop;
import hehe.container.Application;
import hehe.json.Json;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xfw on 17-3-15.
 */
public class Test {
    public static void main(String[] args) {
        //json();
         bean();
        db();
//        Map<String,Object> attrs = new HashMap<>();
//        attrs.put("name",33);
//        attrs.put("age",null);


//        Log.error("test error is ...");
//        LoggerPropertie loggerPropertie = new LoggerPropertie();
//        loggerPropertie.getAttrs("log.logger.easy");
//        Validation validation = new Validation();
//
////        validation.on("name").add(new Verify("required").tip("xxx"))
////                  .on("age",new Verify("required").tip("请输入{min} and {max}")).tip("dfdfd");
//        ;
//        if (validation.validate(new IndexController())) {
//            System.out.println("验证通过" + Math.random());
//        } else {
//            System.out.println("验证未通过" + Math.random() + ",消息:" + validation.getFirstError());
//        }
        //AopManager aop = new AopManager();
//        Aop.registerbehavior(LogBehavior.class,Aop.BEFORE_ADVICE,IndexController.class.getName() + ".ok" );
//        Aop.registerbehavior(LogBehavior.class,Aop.AFTER_ADVICE,IndexController.class.getName() + ".ok" );
//        Aop.registerbehavior(LogBehavior.class,Aop.FINALLY_ADVICE,IndexController.class.getName() + ".ok" );
//        IndexController indexController = Aop.getProxy(new IndexController());
//        indexController.ok();

        // 注册事件行为
        Aop.registerEventBehavior("name", LogBehavior.class);
        // 触发事件
        Aop.triggerEvent("name");





//        RequiredValidator requiredValidator = new RequiredValidator();
//        String name = null;
//        System.out.println("name:" + requiredValidator.validate(name));

//        String ddd = "^(?<controller>\\w+)/(?<action>\\w+)$";
//        String router = "<controller>/<action>";
//        Matcher pathinfoRuleMatcher = Pattern.compile(ddd).matcher(router);
//        String name,pattern;
//        if (pathinfoRuleMatcher.find()) {
//            for (int i = 1; i <= pathinfoRuleMatcher.groupCount();i = i + 1) {
//                name = pathinfoRuleMatcher.group("id");
//                System.out.println("name:" + name);
//            }
//            System.out.println("111");
//        } else {
//            System.out.println("222");
//        }


        //Container container = new Container("/home/xfw/work/java/hehej/app/WEB-INF/bean.xml");
//        System.out.println("action run " + Math.random());
//        //Url url = He.getBean("router");
//        Map<String,Object> attrs = new HashMap<String,Object>(){{
//            put("ref","hehe.router.easy.Easy");
//            put("actionSuffix","Action");
//            put("defaultPackage","app.controller");
//            put("controllerSuffix","Controller");
//        }};
//
//        Url url = new Url(attrs);
//        Map<String,String> rule = new HashMap<String,String>(){{
//            put("pathinfoRule","<controller:\\\\w+>/<action:\\\\w+>");
//            put("urlRule","<controller>/<action>");
//        }};
//
//        url.addRule(rule);
//
//        Controller controller = url.findController("index/user",null);
//
//        System.out.println("controller:" + controller.getController());
//        System.out.println("action:" + controller.getAction());
//
//        String uri = url.createUrl("index/user");
//        System.out.println(uri);
//        System.out.println(uri);


        //bean();
//        String filename = "/home/xfw/work/java/hehej/src/hehe/bean.xml";
//        He.container.loadFromXml(filename);
//        BeanDefinition bean = He.container.getBeanDefinition("bean1");
//
//
//        System.out.println(bean.getId());
//        System.out.println(bean.getRef());


//        String emailPattern = "\\{\\{%(.+?)\\}\\}";
//        Pattern pattern = Pattern.compile(emailPattern);
//        Matcher matcher = pattern.matcher("{{%test}}@qq.com");
//        //验证是否邮箱
//        System.out.println(matcher.find());
//        //得到@符号前的邮箱名  out: test
//        System.out.println(matcher.replaceAll("$1"));
//
//

//        ArrayList d = new ArrayList();
//        d.add(2);
//
//        System.out.println("xxx:" + new ArrayList(){{add(1);}}.getClass());
//        return;
//        long start = System.currentTimeMillis();
//
//
//        User user = new User();
//        SqlMap where = new SqlMap();
//        //String[] UserId = {"110"};
//        where.put("UserId",110);
////        SqlMap andWhere = new SqlMap();
////        andWhere.put("Email","name");
////        andWhere.put("Password","123123");
////        where.add(andWhere);
//////
//////
//        for (int i = 0;i < 1;i++) {
//            Map<String, Object> row = user
//                    .setWhere(where).one();
//            System.out.println(DbManager.get().getLastSql());
//            System.out.println(row.toString());
//        }

        //System.out.println(DbManager.get().getLastSql());
//        DbManager.get().beginTransaction();
//        SqlMap data = new SqlMap();
//        data.put("UserName","x" + Math.random());
//        //data.put("Email","adin@163.com");
//        data.addExp("Email","field","3");
////
////
////        for (int i = 0;i < 10000;i++) {
//            user.setData(data).addOne();
//        DbManager.get().commit();
//        System.out.println(DbManager.get().getLastSql());
//        }
//
//        //return;
//
//
//
//        //return;
//
//        //user.setData(data).addOne();
//
        /*
        SqlMap where = new SqlMap();

        String[] UserId = {"110"};

        where.put("UserId",110);
        //where.put("UserId",110);
//
        where.put("UserName","xxx");

        SqlMap andWhere = new SqlMap();

        andWhere.put("Email","name");
        andWhere.put("Password","123123");

        where.add(andWhere);
        long start = System.currentTimeMillis();
        System.out.println("start:" + start);
//
        SqlMap fields = new SqlMap();
        fields.add("UserId","UserName");
        SqlMap order = new SqlMap();
        order.put("UserId","desc");
        order.put("UserName","asc");

        SqlMap groups = new SqlMap();
        groups.add("UserId","UserName");
        SqlMap having = new SqlMap();
        having.addExp("UserId","gt",1);
        //for (int i = 0;i < 10000;i++) {
            Map<String, Object> row = user
                    .setField("*")
                    .setAlias("c")
                    .setWhere(where).one();
        //}


//        //fields.add();
//        int row = user.setData(data).setWhere(where).updateOne();
        //for (int i = 0;i < 10000;i++) {
//            Map<String, Object> row = user
//                    .setField(fields)
//                    .setAlias("cc")
//                    .setOrder(order)
//                    .setGroup(groups)
//                    .setHaving(having)
//                    .setLock(true)
//                    .setWhere(where).one();
        //}

        System.out.println(DbManager.get().getLastSql());
        //}

        */

//        long end = System.currentTimeMillis();
//        System.out.println("end  :" + end);
//
//        System.out.println("total ms:" + (end-start));

        //System.out.println(row.toString());





    }


    public static void bean()
    {
        String file = "/home/xfw/work/java/hehej/app/WEB-INF/bean.xml";
        Application app = new Application(file);
//
        Address address = He.getBean("address");
        address.find();
//        address.find();
//        String rule = "^/home/xfw/work/java/hehej/target/classes/bean(.?)\\.xml$";
//        String name = "/home/xfw/work/java/hehej/target/classes/bean.xml";
//
//
//        Matcher matcher = Pattern.compile(rule).matcher(name);
//
//        if (matcher.matches()) {
//            System.out.println("yes");
//        } else {
//            System.out.println("no");
//        }


//        ResourcePath path = new ResourcePath();
//
//        String basePath = "$classpath:bean?.xml";
//        Scan scan = new Scan();
//
//        List<String> paths = scan.scanResource(basePath);
//        for (String url:paths) {
//            System.out.println("name:" + url);
//        }


//        String[] paths  = path.getScanPath(name);
//        System.out.println(paths[0]);
//        System.out.println(paths[1]);
//
//
//        String pattern = path.formatPath(name);
//        System.out.println(pattern);
//        String key = "/user/name/beans-.xml";
//        Matcher matcher = Pattern.compile(pattern).matcher(key);
//        if (matcher.matches()) {
//            System.out.println("yes");
//        } else {
//            System.out.println("no");
//        }


        //System.out.println(path.getFullPath("$classpath:name/ok"));
        long workerTaskPooltime = System.currentTimeMillis();
//        Pool workerTaskPool = He.getBean("workers");
//
//        for (int i = 0;i < 1000000;i++) {
//            workerTaskPool.pull(new Runnable(){
//                public void  run()
//                {
//                    System.out.println("耗时:" + (System.currentTimeMillis() - workerTaskPooltime) + " ms");
//                };
//            });
//        }

//
//        //Address address2 = He.getBean(Address.class);
//        address.find();
//
//
//        for (Integer age:address.ages) {
//            System.out.println("age:" + age);
//        }

        //LogManager logManager = new LogManager();
        //Log.error("test:" + Math.random());
        //System.out.println("age:");
//
//        while (true) {
//
//            try {
//                Thread.sleep(1000);
//                String errormsg = "my name is:" + Math.random();
//                Log.error(errormsg);
//                System.out.println("main:" + errormsg);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }

        //List<> ages = address.ages;
//
//
//        //He.container.loadFromXml(file);
//        long start = System.currentTimeMillis();
//
//        Order order = (Order)He.container.getBean("order");
//        long end = System.currentTimeMillis();
//
//        DbManager db = (DbManager)He.container.getBean("db");
//        User user = new User();
//
//        SqlMap where = SqlMap.mSet("UserId",10);
//        SqlMap orWhere = SqlMap.mSet("UserId",111)
//                .set("UserName","2222");
//
//        Map<String, Object> row = user
//                .setField("*")
//                .setAlias("c")
//                .setWhere(where)
//                .setOrWhere(orWhere)
//                .one();
//
//
//
//        System.out.println("sql:" + User.getLastSql());
//        System.out.println("result2:" + db.dbOptions.toString());
//        System.out.println("result:" + row.toString());

//        System.out.println("order1 time:" + (end-start));
//
//        long start2 = System.currentTimeMillis();
//
//        Order order2 = (Order)He.container.getBean("order");
//        long end2 = System.currentTimeMillis();
//
//        System.out.println("order2 time:" + (end2-start2));


//        System.out.println("id:" + order.getId());
//        System.out.println("name:" + order.getName());
//        System.out.println("rule:" + order.getRule());

//        DbManager db = (DbManager)He.container.getBean("db");
//
//        System.out.println("------------------");
//        System.out.println(db.dbOptions);

    }

    public static void xml()
    {
        String name = "/home/xfw/work/java/hehej/src/hehe/bean.xml";
        //int i = String.valueOf(name);

        //System.out.println(age);

    }

    public static void json()
    {
        //BaseJson json = Json.getJson(Json.JACKSON_JSON);
        Map<String,Object> attr = new HashMap<>();
        attr.put("name","1212");
        attr.put("ok","1212");
        //attr.put("User",new Acount());

//

//        String jsonstr = json.format(attr);
//        System.out.println(jsonstr);
//
//
//        Map<String,Object> attr2 = json.parser(jsonstr,Map.class);
//        System.out.println(attr2);

        System.out.println("。。。。。");
//        String jsoniterJson = Json.format(attr);
//        System.out.println(jsoniterJson);
//
//        System.out.println(Json.parser(jsoniterJson,Map.class));

        try {
            String jsoniterJson = Json.format(attr);
            System.out.println(jsoniterJson);
            Map<String,Object> attrs = Json.parser(jsoniterJson,Map.class);
            System.out.println(attrs);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public static void db()
    {
                //He.container.loadFromXml(file);
        long start = System.currentTimeMillis();
        DbManager db = (DbManager) He.container.getBean("db");
//        Order order = (Order)He.container.getBean("order");
//        long end = System.currentTimeMillis();
//        Trans.beginTransaction();
        //User user = new User();
//
//        SqlMap data = new SqlMap();
//        String UserName = "name:" +  Math.random();
//        data.put("UserName",UserName);
//        data.put("RoleId",1);
//
//        SqlMap data2 = new SqlMap();
//        data2.put("UserName",UserName);
//        data2.put("RoleId",2);


//        //data.put("Email","adin@163.com");
//        //data.exp("Email","field","3");
//
////        SqlMap where = SqlMap.mSet("UserId",10);
////        SqlMap orWhere = SqlMap.mSet("UserId",111)
////                .set("UserName","2222");\
//

//
        SqlMap data = SqlMap.make();
        data.put("UserName","name:" +  Math.random());
        data.put("RoleId",1);

        Dao user = Dao.make("{{%users}}","hh");
        User daoUser = new User();
        UserEntity userEntity = new UserEntity();
        userEntity.userName = "xiongdi" + Math.random();
        userEntity.UserId = 350;

        //int result = daoUser.addOne(userEntity);
        //System.out.println("result add:" + result);


        int result = daoUser.updateOne(userEntity);
        System.out.println("result:" + result);


//        Query query = daoUser
//                .field("*")
//                .where("RoleId", new int[]{1,2},"in")
//                .toQuery()
//                .orderBy("UserId","desc")
//                .all();

        List<UserEntity> rows = daoUser
                .field("*")
                .where("UserId", 350)
               // .union(query)
                .all(UserEntity.class);

        for (UserEntity entity:rows) {
            System.out.println("entity:" + entity.userName);
        }



        // 更新操作
//        SqlMap data = SqlMap.make();
//        data.put("UserName","rand:" + Math.random());
//        int result = daoUser.data(data).where("RoleId",new int[]{1,2,3},"in").updateAll();
//        String UserName = "name:" +  Math.random();
//        data.put("UserName",UserName);
//        data.put("RoleId",1);

        //Trans.rollback();

        //Map<String,String> result = user.invoke("db");
        //System.out.println("result:" + result);
        System.out.println(db.getLastSql());
        //System.out.println("result:" + row);

        //System.out.println(row);
        //Trans.beginTransaction();

//        DbcThread dbcThread1 = new DbcThread("db");
//        DbcThread dbcThread5 = new DbcThread("db");
//        DbThread dbcThread2 = new DbThread("db");
//        DbThread dbcThread3 = new DbThread("db");
//        DbThread dbcThread4 = new DbThread("db");
//        dbcThread1.start();
//        dbcThread2.start();
//        dbcThread3.start();
//        dbcThread4.start();
//        dbcThread5.start();

        // 多线程插入db
    }

}